package com.mindcraft.chat.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mindcraft.base.model.MindCraftResult;
import com.mindcraft.chat.mapper.ImChatUserMessageMapper;
import com.mindcraft.chat.po.ImChatUserMessage;
import com.mindcraft.chat.service.ImChatUserMessageService;
import com.mindcraft.chat.vo.ImChatUserMessageVo;
import com.mindcraft.chat.vo.MessageRequestVo;
import com.mindcraft.chat.vo.SystemMessageVo;
import com.mindcraft.user.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ImChatUserMessageServiceImpl extends ServiceImpl<ImChatUserMessageMapper, ImChatUserMessage> implements ImChatUserMessageService {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public MindCraftResult listFriendMessage(MessageRequestVo messageRequestVo) {

        String key ="chat:"+ messageRequestVo.getUserId() + ":" + messageRequestVo.getFriendId();
        String key1 ="chat:"+ messageRequestVo.getFriendId() + ":" + messageRequestVo.getUserId();

        if (redisTemplate.hasKey(key) || redisTemplate.hasKey(key1)) {
            List<ImChatUserMessageVo> sendMessageList = new ArrayList<>();
            List<ImChatUserMessageVo> receiveMessageList = new ArrayList<>();


            List<Map<String, List<ImChatUserMessageVo>>> resultMapList = new ArrayList<>();

// 创建两个空的 Map 对象，用于存放发送者和接收者的消息
            Map<String, List<ImChatUserMessageVo>> senderMap = new HashMap<>();
            Map<String, List<ImChatUserMessageVo>> receiverMap = new HashMap<>();

            if (redisTemplate.hasKey(key)) {
                List<String> chatRecordList = redisTemplate.opsForList().range(key, 0, -1);
                for (String chatRecordJson : chatRecordList) {
                    ImChatUserMessageVo chatRecord = JSON.parseObject(chatRecordJson, ImChatUserMessageVo.class);
                    sendMessageList.add(chatRecord);
                }
                senderMap.put("sendMessage", sendMessageList);
            }
            if(redisTemplate.hasKey(key1)){

                List<String> chatRecordList = redisTemplate.opsForList().range(key1, 0, -1);
                for (String chatRecordJson : chatRecordList) {
                    ImChatUserMessageVo chatRecord = JSON.parseObject(chatRecordJson, ImChatUserMessageVo.class);
                    receiveMessageList.add(chatRecord);
                }

                receiverMap.put("receiveMessage", receiveMessageList);

            }


            resultMapList.add(receiverMap);
            resultMapList.add(senderMap);

            messageRequestVo.setRecords(resultMapList);

            return MindCraftResult.success(messageRequestVo);
        } else {

            MessageRequestVo page = lambdaQuery()
                    .eq(ImChatUserMessage::getFromId, messageRequestVo.getUserId())
                    .eq(ImChatUserMessage::getToId, messageRequestVo.getFriendId())
                    .orderByDesc(ImChatUserMessage::getCreateTime)
                    .or()
                    .eq(ImChatUserMessage::getFromId, messageRequestVo.getFriendId())
                    .eq(ImChatUserMessage::getToId, messageRequestVo.getUserId())
                    .orderByDesc(ImChatUserMessage::getCreateTime)
                    .page(messageRequestVo);

            List<ImChatUserMessage> records = messageRequestVo.getRecords();

            if (!CollectionUtils.isEmpty(records)) {
                List<Map<String, List<ImChatUserMessageVo>>> resultMapList = new ArrayList<>();

// 创建两个空的 Map 对象，用于存放发送者和接收者的消息
                Map<String, List<ImChatUserMessageVo>> senderMap = new HashMap<>();
                Map<String, List<ImChatUserMessageVo>> receiverMap = new HashMap<>();

                for (ImChatUserMessage record : records) {
                    ImChatUserMessageVo imChatUserMessageVo = new ImChatUserMessageVo();
                    imChatUserMessageVo.setId(record.getId());
                    imChatUserMessageVo.setContent(record.getContent());
                    imChatUserMessageVo.setCreateTime(record.getCreateTime());

                    // 判断是谁发给谁的
                    if (record.getToId().equals(messageRequestVo.getFriendId())) {
                        // 将消息添加到接收者的 Map 中
                        //用户发送的
                        List<ImChatUserMessageVo> existingMessages = senderMap.get("sendMessage");

                        if (!CollectionUtils.isEmpty(existingMessages)) {
                            existingMessages.add(imChatUserMessageVo);
                        }else{
                            // 如果不存在，则创建新的消息列表，并将当前消息添加到列表中
                            List<ImChatUserMessageVo> messageList = new ArrayList<>();
                            messageList.add(imChatUserMessageVo);
                            senderMap.put("sendMessage", messageList);
                        }
                    } else if (record.getToId().equals(messageRequestVo.getUserId())) {
                        // 发送者的 Map 中查找是否已存在该接收者的消息列表
                        List<ImChatUserMessageVo> existingMessages = receiverMap.get("receiveMessage");
                        if (!CollectionUtils.isEmpty(existingMessages)) {
                            // 如果已存在，则将当前消息添加到列表中
                            existingMessages.add(imChatUserMessageVo);
                        } else {
                            // 如果不存在，则创建新的消息列表，并将当前消息添加到列表中
                            List<ImChatUserMessageVo> messageList = new ArrayList<>();
                            messageList.add(imChatUserMessageVo);
                            receiverMap.put("receiveMessage", messageList);
                        }
                    }
                }

// 将发送者和接收者的 Map 添加到结果列表中
                resultMapList.add(senderMap);
                resultMapList.add(receiverMap);

                messageRequestVo.setRecords(resultMapList);
            }


            return MindCraftResult.success(page);
        }

    }


    //系统消息
    @Override
    public MindCraftResult listSystemMessage(SystemMessageVo systemMessageVo) {


        lambdaQuery()
                .select(ImChatUserMessage::getId, ImChatUserMessage::getContent, ImChatUserMessage::getCreateTime)
                .eq(ImChatUserMessage::getFromId, "-1")
                .orderByDesc(ImChatUserMessage::getCreateTime)
                .page(systemMessageVo);


        return MindCraftResult.success(systemMessageVo);
    }
}
